<template>
  <view class="p-20 publish-cook">
    <up-form
        labelPosition="top"
        :model="formData"
        :rules="rules"
        ref="formRef"
        labelWidth="150rpx"
    >
      <up-form-item
          v-for="(item, index) in formConfig"
          :key="index"
          :label="item.label"
          :prop="item.prop"
      >
        <component
            :is="item.component"
            v-model="formData[item.prop]"
            v-bind="item.attrs"
            v-on="item.events"
        />
      </up-form-item>

      <up-form-item label="所需食材" prop="foods">
        <view style="width: 100%">
          <view
              v-for="(food, index) in formData.foods"
              :key="index"
              style="display: flex;margin-bottom: 20rpx"
          >
            <up-input
                v-model="food.name"
                placeholder="食材名称"
                clearable
                style="width: 80%;margin-right: 10rpx"
                maxlength="20"
            />
            <up-input
                v-model="food.unit"
                placeholder="食材数量"
                clearable
                style="flex: 1"
                maxlength="10"
            />
            <up-icon @click="removeFood(index)" name="trash-fill" size="20" color="#ff6d70"
                     style="margin-left: 20rpx"></up-icon>
          </view>
          <up-button plain text="添加食材" type="success" @click="addFood"></up-button>
        </view>
      </up-form-item>

      <up-form-item label="制作步骤" prop="steps">
        <view style="width: 100%">
          <view
              v-for="(step, index) in formData.steps"
              :key="index"
              style="display: flex;margin-bottom: 20rpx"
          >
            <up-textarea
                v-model="formData.steps[index]"
                placeholder="步骤"
                maxlength="200"
                count
            />
            <up-icon @click="removeSteps(index)" name="trash-fill" size="20" color="#ff6d70"
                     style="margin-left: 20rpx"></up-icon>
          </view>
          <up-button plain text="添加步骤" type="success" @click="addSteps"></up-button>
        </view>
      </up-form-item>

      <up-form-item>
        <view style="width: 100%">
          <up-button color="#ff6d70" style="margin-bottom: 20rpx" @click="handleSubmit">发布</up-button>
          <up-button plain type="primary" @click="handleSave">保存</up-button>
        </view>
      </up-form-item>
    </up-form>
  </view>
</template>

<script setup lang="ts">
import {ref, reactive} from 'vue';
import {onLoad} from '@dcloudio/uni-app'
import {getFormConfig, uploadFile} from "@/util/form/publishConfig";

// 表单数据
const formData = reactive({
  type: 1,
  title: '',
  describe: '',
  foods: [] as Array<{ name?: string; unit?: string }>,
  steps: [] as string[],
  needMinutes: 0,
  complexity: 0,
  imgs: [] as any[]
})

// 表单验证规则
const rules = reactive({
  title: [
    {required: true, message: '请输入标题', trigger: 'blur'},
    {min: 5, max: 50, message: '长度在 5 到 50 个字符', trigger: 'blur'}
  ],
  describe: [
    {required: true, message: '请输入描述', trigger: 'blur'}
  ]
})

// 表单引用
const formRef = ref(null)

// 表单方法
const selectItem = (item: any) => {
  console.log('Selected item:', item)
}

const handleDeleteImage = (event: any) => {
  formData.imgs.splice(event.index, 1)
}

const handleImageUpload = async (event: any) => {
  try {
    const lists = [].concat(event.file)
    const fileListLen = formData.imgs.length

    // 添加上传中状态
    lists.map((item: any) => {
      formData.imgs.push({
        ...item,
        status: 'uploading',
        message: '上传中'
      })
    })

    // 逐个上传
    for (let i = 0; i < lists.length; i++) {
      const result = await uploadFile(lists[i].url)
      const item = formData.imgs[fileListLen + i]
      formData.imgs.splice(fileListLen + i, 1, {
        ...item,
        status: 'success',
        message: '',
        url: result
      })
    }
  } catch (error) {
    console.error('上传失败:', error)
    uni.showToast({
      title: '上传失败',
      icon: 'none'
    })
  }
}

// 获取表单配置
const formConfig = getFormConfig(formData, {
  selectItem,
  handleDeleteImage,
  handleImageUpload
})

// 食材操作方法
const addFood = () => {
  formData.foods.push({name: '', unit: ''})
}

const removeFood = (index: number) => {
  formData.foods.splice(index, 1)
}

// 步骤操作方法
const addSteps = () => {
  formData.steps.push('')
}

const removeSteps = (index: number) => {
  formData.steps.splice(index, 1)
}

// 表单提交方法
const handleSubmit = () => {
  try {
    formRef.value.validate()
    console.log('表单数据:', formData)
    uni.showToast({
      title: '提交成功',
      icon: 'success'
    })
    // 这里可以添加提交到服务器的逻辑
  } catch (error) {
    console.error('表单验证失败:', error)
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    })
  }
}

const handleSave = () => {
  console.log('保存数据:', formData)
  uni.showToast({
    title: '保存成功',
    icon: 'success'
  })
  // 这里可以添加保存逻辑
}

onLoad(() => {
  // 监听键盘高度变化 (仅APP和微信小程序)
  // #ifdef APP || MP-WEIXIN
  uni.onKeyboardHeightChange((res) => {
    console.log('键盘高度:', res.height)
  })
  // #endif
})
</script>

<style scoped lang="scss">
@import "@/static/css/index.css";

.publish-cook {
  margin: 20rpx;
  background: #fff;
  border-radius: 10rpx;
  box-sizing: border-box;
}
</style>
